<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta name="baidu-site-verification" content="code-KNXLvfbWBj" />
    <meta charset="utf-8">
    <meta name="keywords" content="Scala笔记, Aunean&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Scala笔记 | Aunean&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="Aunean's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>





<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Aunean&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/navigate" class="waves-effect waves-light">
      
      <i class="fas fa-location-arrow" style="zoom: 0.6;"></i>
      
      <span>导航</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Aunean&#39;s Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/navigate" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-location-arrow"></i>
			
			导航
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/Aunean-ls" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/Aunean-ls" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/u024.webp')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Scala笔记</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Scala/">
                                <span class="chip bg-color">Scala</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="post-category">
                                学习笔记
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-05-04
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-08-04
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    9.4k
                </div>
                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="Scala学习笔记"><a href="#Scala学习笔记" class="headerlink" title="Scala学习笔记"></a>Scala学习笔记</h1><h2 id="第一章-Scala的概述"><a href="#第一章-Scala的概述" class="headerlink" title="第一章  Scala的概述"></a>第一章  Scala的概述</h2><ul>
<li><p>Scala 是一门多范式（multi-paradigm）的编程语言，设计初衷是要集成面向对象编程和函数式编程的各种特性。</p>
</li>
<li><p>Scala 运行在 Java 虚拟机上，并兼容现有的 Java 程序。</p>
</li>
<li><p>Scala 源代码被编译成 Java 字节码，所以它可以运行于 JVM 之上，并可以调用现有的 Java 类库。</p>
</li>
</ul>
<h3 id="1-1-Scala-和-Java-以及-JVM的关系分析图"><a href="#1-1-Scala-和-Java-以及-JVM的关系分析图" class="headerlink" title="1.1 Scala 和 Java 以及 JVM的关系分析图"></a>1.1 Scala 和 Java 以及 JVM的关系分析图</h3><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/PIcb6EWZSiMXgCy.png" alt="关系图"></p>
<h3 id="1-2-Scala语言的特点"><a href="#1-2-Scala语言的特点" class="headerlink" title="1.2 Scala语言的特点"></a>1.2 Scala语言的特点</h3><h4 id="1-2-1-面向对象特性"><a href="#1-2-1-面向对象特性" class="headerlink" title="1.2.1 面向对象特性"></a>1.2.1 面向对象特性</h4><p>Scala是一种纯面向对象的语言，每个值都是对象。对象的数据类型以及行为由类和特质描述。</p>
<p>类抽象机制的扩展有两种途径：一种途径是子类继承，另一种途径是灵活的混入机制。这两种途径能避免多重继承的种种问题。</p>
<h4 id="1-2-2-函数式编程"><a href="#1-2-2-函数式编程" class="headerlink" title="1.2.2 函数式编程"></a>1.2.2 函数式编程</h4><p>Scala也是一种函数式语言，其函数也能当成值来使用。Scala提供了轻量级的语法用以定义匿名函数，支持高阶函数，允许嵌套多层函数，并支持柯里化。Scala的case class及其内置的模式匹配相当于函数式编程语言中常用的代数类型。</p>
<p>更进一步，程序员可以利用Scala的模式匹配，编写类似正则表达式的代码处理XML数据。</p>
<h4 id="1-2-3-静态类型"><a href="#1-2-3-静态类型" class="headerlink" title="1.2.3 静态类型"></a>1.2.3 静态类型</h4><p>Scala具备类型系统，通过编译时检查，保证代码的安全性和一致性。类型系统具体支持以下特性：</p>
<ul>
<li>泛型类</li>
<li>协变和逆变</li>
<li>标注</li>
<li>类型参数的上下限约束</li>
<li>把类别和抽象类型作为对象成员</li>
<li>复合类型</li>
<li>引用自己时显式指定类型</li>
<li>视图</li>
<li>多态方法</li>
</ul>
<h4 id="1-2-4-扩展性"><a href="#1-2-4-扩展性" class="headerlink" title="1.2.4 扩展性"></a>1.2.4 扩展性</h4><p>Scala的设计秉承一项事实，即在实践中，某个领域特定的应用程序开发往往需要特定于该领域的语言扩展。Scala提供了许多独特的语言机制，可以以库的形式轻易无缝添加新的语言结构：</p>
<ul>
<li>任何方法可用作前缀或后缀操作符</li>
<li>可以根据预期类型自动构造闭包。</li>
</ul>
<h4 id="1-2-5-并发性"><a href="#1-2-5-并发性" class="headerlink" title="1.2.5 并发性"></a>1.2.5 并发性</h4><p>Scala使用Actor作为其并发模型，Actor是类似线程的实体，通过邮箱发收消息。Actor可以复用线程，因此可以在程序中可以使用数百万个Actor,而线程只能创建数千个。在2.10之后的版本中，使用Akka作为其默认Actor实现。</p>
<h3 id="1-3-Scala程序开发注意事项"><a href="#1-3-Scala程序开发注意事项" class="headerlink" title="1.3 Scala程序开发注意事项"></a>1.3 Scala程序开发注意事项</h3><ol>
<li>Scala源文件以 .scala 为扩展名</li>
<li>Scala程序的执行入口是 main() 函数</li>
<li>Scala语言严格区分大小写</li>
<li>Scala方法由一条条语句构成,每个语句后不需要分号</li>
<li>如果在同一行有多条语句,除了最后一条语句不需要分号,其他语句需要分号</li>
</ol>
<h3 id="1-4-Scala语言转义字符"><a href="#1-4-Scala语言转义字符" class="headerlink" title="1.4 Scala语言转义字符"></a>1.4 Scala语言转义字符</h3><table>
<thead>
<tr>
<th>符号</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>\t</td>
<td>制表符</td>
</tr>
<tr>
<td>\n</td>
<td>换行符</td>
</tr>
<tr>
<td>\</td>
<td>一个 \</td>
</tr>
<tr>
<td>"</td>
<td>一个 “</td>
</tr>
<tr>
<td>\r</td>
<td>一个回车</td>
</tr>
</tbody></table>
<h3 id="1-5-Scala三种输出方式"><a href="#1-5-Scala三种输出方式" class="headerlink" title="1.5 Scala三种输出方式"></a>1.5 Scala三种输出方式</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter01

<span class="token keyword">object</span> printDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> str1<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"hello"</span>
    <span class="token keyword">val</span> str2 <span class="token operator">=</span> <span class="token string">" world!"</span>
    println<span class="token punctuation">(</span>str1 <span class="token operator">+</span> str2<span class="token punctuation">)</span>

    <span class="token keyword">val</span> name <span class="token operator">=</span> <span class="token string">"Tom"</span>
    <span class="token keyword">val</span> age <span class="token operator">=</span> <span class="token number">10</span>
    <span class="token keyword">val</span> sal<span class="token operator">:</span> <span class="token builtin">Float</span> <span class="token operator">=</span> <span class="token number">10.56f</span>
    <span class="token keyword">val</span> height<span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> <span class="token number">180.15</span>
    <span class="token comment" spellcheck="true">// 格式化输出</span>
    printf<span class="token punctuation">(</span><span class="token string">"名字是=%s 年龄是%d 薪水是%.2f 身高是%.3f"</span><span class="token punctuation">,</span> name<span class="token punctuation">,</span> age<span class="token punctuation">,</span> sal<span class="token punctuation">,</span> height<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true">// scala支持使用$输出内容，编译器回去解析$对应的变量</span>
    println<span class="token punctuation">(</span>s<span class="token string">"\n个人信息如下：\n名字$name \n年龄$age \n薪水$sal"</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 如果在字符串中出现类似${age + 10}则表示{}是一个表达式</span>
    println<span class="token punctuation">(</span>s<span class="token string">"\n个人信息如下2：\n名字${name} \n年龄${age+10} \n薪水${sal*10}"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h2 id="第二章-变量"><a href="#第二章-变量" class="headerlink" title="第二章 变量"></a>第二章 变量</h2><h3 id="2-1-变量的介绍"><a href="#2-1-变量的介绍" class="headerlink" title="2.1 变量的介绍"></a>2.1 变量的介绍</h3><h4 id="2-1-1-概念"><a href="#2-1-1-概念" class="headerlink" title="2.1.1 概念"></a>2.1.1 概念</h4><blockquote>
<p>变量相当于内存中一个数据存储空间的表示,可以把变量看作是一个房间门牌号,通过门派号我们可以找到房间,而通过变量名可以访问到变量值</p>
</blockquote>
<h4 id="2-1-2-变量使用的基本步骤"><a href="#2-1-2-变量使用的基本步骤" class="headerlink" title="2.1.2 变量使用的基本步骤"></a>2.1.2 变量使用的基本步骤</h4><ol>
<li>声明/定义变量(Scala 要求变量声明时初始化)</li>
<li>使用</li>
</ol>
<h3 id="2-2-Scala变量的基本使用"><a href="#2-2-Scala变量的基本使用" class="headerlink" title="2.2 Scala变量的基本使用"></a>2.2 Scala变量的基本使用</h3><h4 id="2-2-1-快速入门"><a href="#2-2-1-快速入门" class="headerlink" title="2.2.1 快速入门"></a>2.2.1 快速入门</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">object</span> VarDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token number">10</span>
    <span class="token keyword">var</span> sal<span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> <span class="token number">10.9</span>
    <span class="token keyword">var</span> isPass<span class="token operator">:</span> <span class="token builtin">Boolean</span> <span class="token operator">=</span> <span class="token boolean">true</span>
    <span class="token comment" spellcheck="true">// 在Scala中，小数默认为Double，整数默认为Int</span>
    <span class="token keyword">var</span> score<span class="token operator">:</span> <span class="token builtin">Float</span> <span class="token operator">=</span> <span class="token number">70.9f</span>
    println<span class="token punctuation">(</span>age<span class="token punctuation">,</span> sal<span class="token punctuation">)</span>
    print<span class="token punctuation">(</span>s<span class="token string">"$age, $sal"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
</code></pre>
<h3 id="2-3-Scala变量使用说明"><a href="#2-3-Scala变量使用说明" class="headerlink" title="2.3 Scala变量使用说明"></a>2.3 Scala变量使用说明</h3><h4 id="2-3-1-变量声明基本语法"><a href="#2-3-1-变量声明基本语法" class="headerlink" title="2.3.1 变量声明基本语法"></a>2.3.1 变量声明基本语法</h4><blockquote>
<p>val | var 变量名 [: 变量类型] = 变量值</p>
</blockquote>
<h4 id="2-3-2-注意事项"><a href="#2-3-2-注意事项" class="headerlink" title="2.3.2 注意事项"></a>2.3.2 注意事项</h4><ol>
<li>声明变量时,类型可以省略(编译器自动推导,即类型推导)</li>
<li>类型确定后,就不能修改,说明Scala是强语言类型语言</li>
<li>在声明/定义一个变量时，可以使用 var 或者 val 来修饰，var 修饰的变量可以改变，val 修饰的变量不可以改</li>
<li>val修饰的变量在编译后,等同于加上final</li>
<li>声明变量时,需要初始值</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter01<span class="token punctuation">.</span>vars

<span class="token keyword">object</span> VarDemo02 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 类型推导</span>
    <span class="token keyword">var</span> num <span class="token operator">=</span> <span class="token number">10</span>
    <span class="token comment" spellcheck="true">// 方式一：可以利用idea的提示来证明</span>
    <span class="token comment" spellcheck="true">// 方式二：使用isInstanceOf[Int]判断</span>
    println<span class="token punctuation">(</span>num<span class="token punctuation">.</span>isInstanceOf<span class="token punctuation">[</span><span class="token builtin">Int</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// true</span>

    <span class="token comment" spellcheck="true">// 类型确定后，就不能修改，说明Scala是强类型语言</span>
    <span class="token comment" spellcheck="true">// num = 2.3</span>

    <span class="token comment" spellcheck="true">// 在声明/定义一个变量时，可以使用 var 或者 val 来修饰，</span>
    <span class="token comment" spellcheck="true">// var 修饰的变量可以改变，val 修饰的变量不可以改</span>
    <span class="token keyword">var</span> age <span class="token operator">=</span> <span class="token number">10</span>
    age <span class="token operator">=</span> <span class="token number">30</span>
    <span class="token comment" spellcheck="true">// val 修饰的变量在编译后，等同于加上了 final</span>
    <span class="token keyword">val</span> num2 <span class="token operator">=</span> <span class="token number">30</span>
    <span class="token comment" spellcheck="true">// num2 = 23 //val 修饰的变量不可以改</span>
    println<span class="token punctuation">(</span>num2<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true">/*
      Scala设计者为什么设计 var 和 val？
      1.在实际编程中，我们更多的需求是获取/创建一个对象后，读取该对象的属性，
      或者是修改对象的属性值，很少去改变这个对象本身，这时，我们就可以使用 val。
      2.val 没有线程安全问题，因此效率高，Scala的设计者推荐使用 val。
      3.如果对象需要改变，则使用 var
     */</span>

    <span class="token keyword">val</span> dog <span class="token operator">=</span> <span class="token keyword">new</span> Dog
    <span class="token comment" spellcheck="true">// dog = new Dog // Reassignment to val</span>
    dog<span class="token punctuation">.</span>age <span class="token operator">=</span> <span class="token number">90</span>
    dog<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"小黑"</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> Dog <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// 声明一个age</span>
  <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token number">0</span>
  <span class="token comment" spellcheck="true">// 声明名字</span>
  <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">""</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="2-4-数据类型"><a href="#2-4-数据类型" class="headerlink" title="2.4 数据类型"></a>2.4 数据类型</h3><ul>
<li>Scala与Java有着相同的数据类型，在Scala中数据类型都是对象，Scala没有Java中的原生类型</li>
<li>Scala数据类型分为两大类 AnyVal（值类型）和AnyRef（引用类型）</li>
</ul>
<h4 id="2-4-1-Scala数据类型体系一览图"><a href="#2-4-1-Scala数据类型体系一览图" class="headerlink" title="2.4.1 Scala数据类型体系一览图"></a>2.4.1 Scala数据类型体系一览图</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210417155646602.png" alt="体系图"></p>
<ul>
<li>在Scala中有一个根类型Any，它是所有类的父类</li>
<li>Scala中一切皆对象，分为两大类 AnyVal（值类型）和AnyRef（引用类型），都是Any子类</li>
<li>Null类型是Scala的特别类型，它只有一个值 null，它是 bottom class，是所有 AnyRef 类型的子类</li>
<li>Nothing 类型也是bottom class，它是所有类的子类，在开发中通常可以将 Nothing 类型的值返回给任意变量或者函数，这里抛出异常使用很多</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210417160333556.png" alt="image-20210417160333556"></p>
<ul>
<li>在Scala中仍然遵守低精度的值像高精度的值自动转换（implicit conversion 隐式转换）</li>
</ul>
<h4 id="2-4-2-Scala数据类型列表"><a href="#2-4-2-Scala数据类型列表" class="headerlink" title="2.4.2 Scala数据类型列表"></a>2.4.2 Scala数据类型列表</h4><table>
<thead>
<tr>
<th>数据类型</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>Byte</td>
<td>8位有符号补码整数。数值区间为 -128~127</td>
</tr>
<tr>
<td>Short</td>
<td>16位有符号补码整数。数值区间为 -32768~32767</td>
</tr>
<tr>
<td>Int</td>
<td>32位有符号补码整数。数值区间为 -2147483648 到 2147483647</td>
</tr>
<tr>
<td>Long</td>
<td>64位有符号补码整数。数值区间为 -9223372036854775808 到 9223372036854775807</td>
</tr>
<tr>
<td>Float</td>
<td>32 位, IEEE 754标准的单精度浮点数</td>
</tr>
<tr>
<td>Double</td>
<td>64 位 IEEE 754标准的双精度浮点数</td>
</tr>
<tr>
<td>Char</td>
<td>16位无符号Unicode字符, 区间值为 U+0000 到 U+FFFF</td>
</tr>
<tr>
<td>String</td>
<td>字符序列</td>
</tr>
<tr>
<td>Boolean</td>
<td>true或false</td>
</tr>
<tr>
<td>Unit</td>
<td>表示无值，和其他语言中void等同。用作不返回任何结果的方法的结果类型。Unit只有一个实例值，写成()</td>
</tr>
<tr>
<td>Null</td>
<td>null</td>
</tr>
<tr>
<td>Nothing</td>
<td>Nothing类型在Scala的类层级的最低端；它是任何其他类型的子类型</td>
</tr>
<tr>
<td>Any</td>
<td>Any是所有其他类的超类</td>
</tr>
<tr>
<td>AnyRef</td>
<td>AnyRef类是Scala里所有引用类(reference class)的基类</td>
</tr>
</tbody></table>
<h3 id="2-5-Unit类型、Null类型和Nothing类型"><a href="#2-5-Unit类型、Null类型和Nothing类型" class="headerlink" title="2.5 Unit类型、Null类型和Nothing类型"></a>2.5 Unit类型、Null类型和Nothing类型</h3><h4 id="2-5-1-使用细节"><a href="#2-5-1-使用细节" class="headerlink" title="2.5.1 使用细节"></a>2.5.1 使用细节</h4><ol>
<li>Null类只有一个实例对象，null，类似与Java中null引用。null可以赋值给任意引用类型(AnyRef)，但是不能赋值给值类型(AnyVal: 比如 Int,Float, Char, Boolean, Long, Double, Byte, Short)</li>
<li>Unit等价于Java的void，只有一个实例值()</li>
<li>Nothing可以作为没有正常返回值的方法的返回类型，非常直观的告诉你这个方法不会正常返回，而且由于Nothing是其他任意类型的子类，它还能跟要求返回值的方法兼容</li>
</ol>
<h3 id="2-6-标识符的命名规范"><a href="#2-6-标识符的命名规范" class="headerlink" title="2.6 标识符的命名规范"></a>2.6 标识符的命名规范</h3><h4 id="2-6-1-标识符概念"><a href="#2-6-1-标识符概念" class="headerlink" title="2.6.1 标识符概念"></a>2.6.1 标识符概念</h4><ul>
<li>Scala对各种变量、方法、函数等命名时使用的字符序列称为标识符</li>
<li>凡是自己可以命名的地方都叫标识符</li>
</ul>
<h4 id="2-6-2-标识符的命名规则"><a href="#2-6-2-标识符的命名规则" class="headerlink" title="2.6.2 标识符的命名规则"></a>2.6.2 标识符的命名规则</h4><ul>
<li>首字符为字母，后续字符任意字母和数字，美元符号，可后接下划线</li>
<li>数字不可以开头</li>
<li>首字符为操作符（比如 + - * ）后续字符也需跟操作符，至少一个</li>
<li>操作符（比如 + - * /）不能在标识符中间和最后</li>
<li>用反引号``包括任意字符串，即使是关键字(39个)也可以</li>
</ul>
<h4 id="2-6-3-标识符的命名规范"><a href="#2-6-3-标识符的命名规范" class="headerlink" title="2.6.3 标识符的命名规范"></a>2.6.3 标识符的命名规范</h4><ul>
<li>包名：尽量采取有意义的包名，简短，有意义</li>
<li>变量名、函数名、方法名采用驼峰法。</li>
</ul>
<h3 id="2-7-Scala的关键字"><a href="#2-7-Scala的关键字" class="headerlink" title="2.7 Scala的关键字"></a>2.7 Scala的关键字</h3><blockquote>
<p>package    import    class    object    trait    extends    with    type</p>
<p>forSome    private    protected    abstract    sealed    final    implicit</p>
<p>override    try    catch    finally    throw    if    else    match    case    do</p>
<p>while    for    return    yield    def    val    var    this    super    new</p>
<p>true    false    null</p>
</blockquote>
<h2 id="第三章-运算符"><a href="#第三章-运算符" class="headerlink" title="第三章 运算符"></a>第三章 运算符</h2><h3 id="3-1-运算符"><a href="#3-1-运算符" class="headerlink" title="3.1 运算符"></a>3.1 运算符</h3><h4 id="3-1-1-算术运算符"><a href="#3-1-1-算术运算符" class="headerlink" title="3.1.1 算术运算符"></a>3.1.1 算术运算符</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165214493.png" alt="算术运算符"></p>
<h4 id="3-1-2-关系运算符"><a href="#3-1-2-关系运算符" class="headerlink" title="3.1.2 关系运算符"></a>3.1.2 关系运算符</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165321295.png" alt="关系运算符"></p>
<h4 id="3-1-3-逻辑运算符"><a href="#3-1-3-逻辑运算符" class="headerlink" title="3.1.3 逻辑运算符"></a>3.1.3 逻辑运算符</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165427731.png" alt="逻辑运算符"></p>
<h4 id="3-1-4-赋值运算符"><a href="#3-1-4-赋值运算符" class="headerlink" title="3.1.4 赋值运算符"></a>3.1.4 赋值运算符</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165510744.png" alt="赋值运算符"></p>
<p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165544522.png" alt="赋值运算符"></p>
<h4 id="3-1-5-位运算符"><a href="#3-1-5-位运算符" class="headerlink" title="3.1.5 位运算符"></a>3.1.5 位运算符</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210420165654402.png" alt="位运算符"></p>
<h3 id="3-2-键盘输入语句"><a href="#3-2-键盘输入语句" class="headerlink" title="3.2 键盘输入语句"></a>3.2 键盘输入语句</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter03<span class="token punctuation">.</span>inputcon

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token keyword">object</span> Demo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
    要求：可以从控制台接收用户信息，【姓名，年龄，薪水】
     */</span>
    println<span class="token punctuation">(</span><span class="token string">"请输入姓名"</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> name <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readLine<span class="token punctuation">(</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"请输入年龄"</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> age <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"请输入工资"</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> salary <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readDouble<span class="token punctuation">(</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>s<span class="token string">"用户的信息位 name=$name age=$age salary=${salary.formatted("</span><span class="token operator">%</span><span class="token punctuation">.</span><span class="token number">2f</span><span class="token string">")}"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h2 id="第四章-程序流程控制"><a href="#第四章-程序流程控制" class="headerlink" title="第四章 程序流程控制"></a>第四章 程序流程控制</h2><h3 id="4-1-分支控制-if-else"><a href="#4-1-分支控制-if-else" class="headerlink" title="4.1 分支控制 if-else"></a>4.1 分支控制 if-else</h3><h4 id="4-1-1-分支-if-else-介绍"><a href="#4-1-1-分支-if-else-介绍" class="headerlink" title="4.1.1 分支 if-else 介绍"></a>4.1.1 分支 if-else 介绍</h4><ul>
<li>分支控制有三种：<ul>
<li>单分支</li>
<li>双分支</li>
<li>多分支</li>
</ul>
</li>
</ul>
<h4 id="4-1-2-单分支案例"><a href="#4-1-2-单分支案例" class="headerlink" title="4.1.2 单分支案例"></a>4.1.2 单分支案例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>ifesle

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token keyword">object</span> Demo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> age <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>age <span class="token operator">>=</span> <span class="token number">18</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"age >= 18"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-1-3-双分支案例"><a href="#4-1-3-双分支案例" class="headerlink" title="4.1.3 双分支案例"></a>4.1.3 双分支案例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>ifesle

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token keyword">object</span> Demo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> age <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>age <span class="token operator">>=</span> <span class="token number">18</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"age >= 18"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"age &lt; 18"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-1-4-多分支案例"><a href="#4-1-4-多分支案例" class="headerlink" title="4.1.4 多分支案例"></a>4.1.4 多分支案例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>ifesle

<span class="token keyword">import</span> breeze<span class="token punctuation">.</span>numerics<span class="token punctuation">.</span>sqrt

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token keyword">object</span> Demo02 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
    成绩为100分时，奖励一辆BMW
    成绩为(80, 99]时，奖励一台笔记本电脑
    成绩为[60, 80]时，奖励一个 iPad
    成绩从控制台输入
     */</span>
    print<span class="token punctuation">(</span><span class="token string">"请输入成绩："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> score <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readDouble<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>score <span class="token operator">></span> <span class="token number">99</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>s<span class="token string">"成绩为${score}分，奖励一辆BMW"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>score <span class="token operator">></span> <span class="token number">80</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>s<span class="token string">"成绩为${score}分，奖励一台笔记本电脑"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>score <span class="token operator">></span> <span class="token number">60</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>s<span class="token string">"成绩为${score}分，奖励一个 iPad"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"再接再厉"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*
    求 ax^2 + bx + c = 0 方程的根，a，b，c分别为函数的参数，
    如果：b^2 - 4ac > 0，则有两个解
    b^2 - 4ac = 0，则有一个解
    b^2 - 4ac &lt; 0，无解
    a=3  b=100  c=6
     */</span>
    <span class="token keyword">val</span> a <span class="token operator">=</span> <span class="token number">3</span>
    <span class="token keyword">val</span> b <span class="token operator">=</span> <span class="token number">100</span>
    <span class="token keyword">val</span> c <span class="token operator">=</span> <span class="token number">6</span>
    <span class="token keyword">var</span> x1 <span class="token operator">=</span> <span class="token number">0.0</span>
    <span class="token keyword">var</span> x2 <span class="token operator">=</span> <span class="token number">0.0</span>
    <span class="token keyword">val</span> res <span class="token operator">=</span> math<span class="token punctuation">.</span>pow<span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">4</span> <span class="token operator">*</span> a <span class="token operator">*</span> c
    <span class="token keyword">if</span> <span class="token punctuation">(</span>res <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      x1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">-</span>b <span class="token operator">+</span> sqrt<span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span> <span class="token operator">*</span> a
      println<span class="token punctuation">(</span>x1<span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>res <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      x1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">-</span>b <span class="token operator">+</span> sqrt<span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span> <span class="token operator">*</span> a
      x2 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">-</span>b <span class="token operator">-</span> sqrt<span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span> <span class="token operator">*</span> a
      println<span class="token punctuation">(</span>x1<span class="token punctuation">)</span>
      println<span class="token punctuation">(</span>x2<span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"无解"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-2-嵌套分支"><a href="#4-2-嵌套分支" class="headerlink" title="4.2 嵌套分支"></a>4.2 嵌套分支</h3><h4 id="4-2-1-基本介绍"><a href="#4-2-1-基本介绍" class="headerlink" title="4.2.1 基本介绍"></a>4.2.1 基本介绍</h4><blockquote>
<p>一个分支结构中有完整的嵌套了另一个完整的分支结构</p>
</blockquote>
<h4 id="4-2-2-应用案例"><a href="#4-2-2-应用案例" class="headerlink" title="4.2.2 应用案例"></a>4.2.2 应用案例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>ifesle

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn
<span class="token comment" spellcheck="true">/*
嵌套分支：在一个分支结构中又完整的嵌套了另一个完整的分支结构，里面的分支的结构称为内层
        分支，外面的分支结构称为外层分支。嵌套分支不要超过三层。
 */</span>
<span class="token keyword">object</span> Exercise02 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
    参加百米运动会，如果用时八秒以内进入决赛，否则提示淘汰。并且根据性别提示进入男子组
    或女子组，输入成绩和性别，进行判断
     */</span>
    print<span class="token punctuation">(</span><span class="token string">"请输入运动员的成绩："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> speed <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readDouble<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>speed <span class="token operator">&lt;=</span> <span class="token number">8</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      print<span class="token punctuation">(</span><span class="token string">"请输入性别："</span><span class="token punctuation">)</span>
      <span class="token keyword">val</span> sex <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readChar<span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>sex <span class="token operator">==</span> <span class="token string">'男'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        println<span class="token punctuation">(</span><span class="token string">"进入男子组"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        println<span class="token punctuation">(</span><span class="token string">"进入女子组"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"你被淘汰"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*
    出票系统：根据淡旺季的月份和年龄，打印票价
    4-10旺季：成人（18-60）：60
             儿童（&lt;18）：半价
             老人（>60）：1/3
        淡季：成人：40
             其他：20
     */</span>
    print<span class="token punctuation">(</span><span class="token string">"请输入月份："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> month <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    print<span class="token punctuation">(</span><span class="token string">"请输入年龄："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> age <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">var</span> price <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token number">4</span> <span class="token operator">&lt;=</span> month <span class="token operator">&amp;&amp;</span> month <span class="token operator">&lt;=</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>age <span class="token operator">&lt;</span> <span class="token number">18</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        price <span class="token operator">=</span> <span class="token number">30</span>
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span><span class="token punctuation">(</span>age <span class="token operator">&lt;=</span> <span class="token number">60</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        price <span class="token operator">=</span> <span class="token number">60</span>
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        price <span class="token operator">=</span> <span class="token number">20</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token number">18</span> <span class="token operator">&lt;=</span> age <span class="token operator">&amp;&amp;</span> age <span class="token operator">&lt;=</span> <span class="token number">60</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        price <span class="token operator">=</span> <span class="token number">40</span>
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        price <span class="token operator">=</span> <span class="token number">20</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span>s<span class="token string">"你的票价为${price}"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-3-for循环控制"><a href="#4-3-for循环控制" class="headerlink" title="4.3 for循环控制"></a>4.3 for循环控制</h3><h4 id="4-3-1-范围数据循环方式-to"><a href="#4-3-1-范围数据循环方式-to" class="headerlink" title="4.3.1 范围数据循环方式 to"></a>4.3.1 范围数据循环方式 to</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1

<span class="token keyword">object</span> ForDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 输入十句 Hello,World</span>
    <span class="token keyword">val</span> start <span class="token operator">=</span> <span class="token number">1</span>
    <span class="token keyword">val</span> end <span class="token operator">=</span> <span class="token number">10</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> start to end<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"Hello,World"</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">// for这种推导式，可以直接对集合进行遍历</span>
    <span class="token keyword">val</span> list <span class="token operator">=</span> List<span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token string">"tom"</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>item <span class="token keyword">&lt;-</span> list<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>item<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-3-2-范围数据循环方式-until"><a href="#4-3-2-范围数据循环方式-until" class="headerlink" title="4.3.2 范围数据循环方式 until"></a>4.3.2 范围数据循环方式 until</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1

<span class="token keyword">object</span> ForUntilDemo02 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 输入十句 Hello,World</span>
    <span class="token keyword">val</span> start <span class="token operator">=</span> <span class="token number">1</span>
    <span class="token keyword">val</span> end <span class="token operator">=</span> <span class="token number">11</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> start until end<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"Hello,World"</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-3-3-循环守卫"><a href="#4-3-3-循环守卫" class="headerlink" title="4.3.3 循环守卫"></a>4.3.3 循环守卫</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1
<span class="token comment" spellcheck="true">/*
  循环守卫，即循环保护式。保护式为true则进入循环体
  内部，否则跳过，类似continue
 */</span>
<span class="token keyword">object</span> ForGuard <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span> <span class="token keyword">if</span> i <span class="token operator">!=</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      print<span class="token punctuation">(</span>i <span class="token operator">+</span> <span class="token string">" "</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>i <span class="token operator">!=</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        print<span class="token punctuation">(</span>i <span class="token operator">+</span> <span class="token string">" "</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-3-4-引入变量"><a href="#4-3-4-引入变量" class="headerlink" title="4.3.4 引入变量"></a>4.3.4 引入变量</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1

<span class="token keyword">object</span> ForVar <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">;</span> j <span class="token operator">=</span><span class="token number">4</span> <span class="token operator">-</span> i<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      print<span class="token punctuation">(</span>j <span class="token operator">+</span> <span class="token string">" "</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 等价</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">val</span> j <span class="token operator">=</span><span class="token number">4</span> <span class="token operator">-</span> i
      print<span class="token punctuation">(</span>j <span class="token operator">+</span> <span class="token string">" "</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-3-5-嵌套循环"><a href="#4-3-5-嵌套循环" class="headerlink" title="4.3.5 嵌套循环"></a>4.3.5 嵌套循环</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1
<span class="token comment" spellcheck="true">/*
  for循环的嵌套
 */</span>
<span class="token keyword">object</span> MultiFor <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">;</span> j <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"i = "</span> <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token string">" j = "</span> <span class="token operator">+</span> j<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span>j <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        println<span class="token punctuation">(</span><span class="token string">"i = "</span> <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token string">" j = "</span> <span class="token operator">+</span> j<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-3-6-循环返回值"><a href="#4-3-6-循环返回值" class="headerlink" title="4.3.6 循环返回值"></a>4.3.6 循环返回值</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>for1
<span class="token comment" spellcheck="true">/*
  yield
 */</span>
<span class="token keyword">object</span> YieldFor <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
      对1 to 10 进行遍历
      yield i 将每次循环得到 i 放入到集合vector中，并返回给res
      i 这里可以是一个代码块，这就意味我们可以对 i 进行处理
      下面这个处理方式，体现了Scala一个重要的语法特点，就是将一个集合中各个数据进行
        处理，并返回给新的集合
     */</span>
    <span class="token keyword">val</span> res <span class="token operator">=</span> <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">10</span><span class="token punctuation">)</span> <span class="token keyword">yield</span> i <span class="token operator">*</span> <span class="token number">2</span>
    <span class="token comment" spellcheck="true">//println(res) // Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)</span>

    <span class="token keyword">val</span> res2 <span class="token operator">=</span> <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">100</span><span class="token punctuation">)</span> <span class="token keyword">yield</span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>i <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        i
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        <span class="token string">"不是偶数"</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span>res2<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-4-while循环控制"><a href="#4-4-while循环控制" class="headerlink" title="4.4 while循环控制"></a>4.4 while循环控制</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>mywhile
<span class="token comment" spellcheck="true">/*
  while的基本使用
 */</span>
<span class="token keyword">object</span> WhileDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 输出十句Hello,World</span>
    <span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"Hello,World"</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
      i <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-5-do…while循环控制"><a href="#4-5-do…while循环控制" class="headerlink" title="4.5 do…while循环控制"></a>4.5 do…while循环控制</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>mydowhile
<span class="token comment" spellcheck="true">/*
  do...while
 */</span>
<span class="token keyword">object</span> Demo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">do</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span><span class="token string">"Hello,World"</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
      i <span class="token operator">+=</span> <span class="token number">1</span>
    <span class="token punctuation">}</span> <span class="token keyword">while</span> <span class="token punctuation">(</span>i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-6-应用案例"><a href="#4-6-应用案例" class="headerlink" title="4.6 应用案例"></a>4.6 应用案例</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>mutifor

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token keyword">object</span> Exercise <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
      1.统计三个班成绩情况，每个班有5名同学，求出各个班的平均分和所有班级的平均分【学生成绩从键盘输入】
      分析思路
      （1）classNum 表示班级个数，stuNum 表示学生个数
      （2）classScore 表示各个班级总分 totalScore 表示所有班级总分
      （3）score 表示各个学生成绩
      （4）使用循环的方式输入成绩
      2.统计三个班及格人数，每个班有五个同学
      3.打印出九九乘法表
     */</span>

    print<span class="token punctuation">(</span><span class="token string">"班级个数："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> classNum <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    print<span class="token punctuation">(</span><span class="token string">"学生个数："</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> stuNum <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">var</span> score <span class="token operator">=</span> <span class="token number">0.0</span>
    <span class="token keyword">var</span> classScore <span class="token operator">=</span> <span class="token number">0.0</span>
    <span class="token keyword">var</span> totalScore <span class="token operator">=</span> <span class="token number">0.0</span>
    <span class="token keyword">var</span> num <span class="token operator">=</span> <span class="token number">0</span> <span class="token comment" spellcheck="true">// 及格人数</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to classNum<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      classScore <span class="token operator">=</span> <span class="token number">0.0</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span>j <span class="token keyword">&lt;-</span> <span class="token number">1</span> to stuNum<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        printf<span class="token punctuation">(</span><span class="token string">"请输入第%d班的第%d个学生的成绩\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> j<span class="token punctuation">)</span>
        score <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readDouble<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>score <span class="token operator">>=</span> <span class="token number">60</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          num <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token punctuation">}</span>
        classScore <span class="token operator">+=</span> score
      <span class="token punctuation">}</span>
      totalScore <span class="token operator">+=</span> classScore
      printf<span class="token punctuation">(</span><span class="token string">"%d班的平均分为%.2f\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> classScore <span class="token operator">/</span> stuNum<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    printf<span class="token punctuation">(</span><span class="token string">"所有班级的平均分为%.2f\n"</span><span class="token punctuation">,</span> classScore <span class="token operator">/</span> <span class="token punctuation">(</span>stuNum <span class="token operator">*</span> classNum<span class="token punctuation">)</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"及格人数："</span> <span class="token operator">+</span> num<span class="token punctuation">)</span>


    <span class="token comment" spellcheck="true">// 九九乘法表</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">9</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span>j <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">9</span> <span class="token keyword">if</span> j <span class="token operator">&lt;=</span> i<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        printf<span class="token punctuation">(</span><span class="token string">"%d * %d = %d\t"</span><span class="token punctuation">,</span> j<span class="token punctuation">,</span> i<span class="token punctuation">,</span> i<span class="token operator">*</span>j<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
      println<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="4-7-while循环的中断"><a href="#4-7-while循环的中断" class="headerlink" title="4.7 while循环的中断"></a>4.7 while循环的中断</h3><h4 id="4-7-1-基本说明"><a href="#4-7-1-基本说明" class="headerlink" title="4.7.1 基本说明"></a>4.7.1 基本说明</h4><blockquote>
<p>Scala内置结构特点去掉了 break 和 continue，为了更好的适应函数化编程。</p>
<p>推荐使用函数式的风格解决 break 和 continue 的功能。</p>
</blockquote>
<h4 id="4-7-2-break的使用"><a href="#4-7-2-break的使用" class="headerlink" title="4.7.2 break的使用"></a>4.7.2 break的使用</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>mybreak

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>util<span class="token punctuation">.</span>control<span class="token punctuation">.</span>Breaks<span class="token punctuation">.</span><span class="token punctuation">{</span>break<span class="token punctuation">,</span> breakable<span class="token punctuation">}</span>

<span class="token keyword">object</span> WhileBreak <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> n <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token comment" spellcheck="true">// breakable()函数</span>
    <span class="token comment" spellcheck="true">// 1.breakable是一个函数：可以接收函数的函数就是高阶函数</span>
    <span class="token comment" spellcheck="true">/* 2.
        def breakable(op: => Unit) {
          try {
            op
          } catch {
            case ex: BreakControl =>
              if (ex ne breakException) throw ex
          }
        }
     */</span>
    <span class="token comment" spellcheck="true">// 3.breakable 对 break()抛出的异常做了处理，代码就可以继续执行</span>
    <span class="token comment" spellcheck="true">// 4.当breakable传入的是代码块时，将()改为{}</span>
    breakable <span class="token punctuation">{</span>
      <span class="token keyword">while</span> <span class="token punctuation">(</span>n <span class="token operator">&lt;=</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        n <span class="token operator">+=</span> <span class="token number">1</span>
        print<span class="token punctuation">(</span>n <span class="token operator">+</span> <span class="token string">"\t"</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">==</span> <span class="token number">7</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment" spellcheck="true">// 1.在Scala中使用函数式的break函数中断循环</span>
          <span class="token comment" spellcheck="true">// 2.def break(): Nothing = { throw breakException }</span>
          break
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"ok~~"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-7-3-continue效果的实现"><a href="#4-7-3-continue效果的实现" class="headerlink" title="4.7.3 continue效果的实现"></a>4.7.3 continue效果的实现</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>mycontinue
<span class="token comment" spellcheck="true">/*
  实现continue的效果
 */</span>
<span class="token keyword">object</span> ContinueDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">10</span> <span class="token keyword">if</span> i <span class="token operator">!=</span> <span class="token number">2</span> <span class="token operator">&amp;&amp;</span> i <span class="token operator">!=</span> <span class="token number">7</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      print<span class="token punctuation">(</span>i <span class="token operator">+</span> <span class="token string">"\t"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="4-7-4-小案例"><a href="#4-7-4-小案例" class="headerlink" title="4.7.4 小案例"></a>4.7.4 小案例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter04<span class="token punctuation">.</span>homework

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>util<span class="token punctuation">.</span>control<span class="token punctuation">.</span>Breaks<span class="token punctuation">.</span><span class="token punctuation">{</span>break<span class="token punctuation">,</span> breakable<span class="token punctuation">}</span>

<span class="token keyword">object</span> HomeWork01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">/*
      100以内的数求和，求出当和第一次大于20的当前数
     */</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token number">0</span>
    breakable<span class="token punctuation">{</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">100</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sum <span class="token operator">+=</span> i
        <span class="token keyword">if</span> <span class="token punctuation">(</span>sum <span class="token operator">></span> <span class="token number">20</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          print<span class="token punctuation">(</span><span class="token string">"当和第一次大于20的当前数："</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
          break
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    println<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">var</span> loop <span class="token operator">=</span> <span class="token boolean">true</span>
    <span class="token keyword">var</span> sum2 <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token keyword">&lt;-</span> <span class="token number">1</span> to <span class="token number">100</span> <span class="token keyword">if</span> loop<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      sum2 <span class="token operator">+=</span> i
      <span class="token keyword">if</span> <span class="token punctuation">(</span>sum2 <span class="token operator">></span> <span class="token number">20</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        loop <span class="token operator">=</span> <span class="token boolean">false</span>
        print<span class="token punctuation">(</span><span class="token string">"循环守卫实现中断 当和第一次大于20的当前数："</span> <span class="token operator">+</span> i<span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="第五章-函数式编程基础"><a href="#第五章-函数式编程基础" class="headerlink" title="第五章 函数式编程基础"></a>第五章 函数式编程基础</h2><h3 id="5-1-介绍"><a href="#5-1-介绍" class="headerlink" title="5.1 介绍"></a>5.1 介绍</h3><ul>
<li>函数式编程是一种编程范式（programming paradigm）</li>
<li>它属于结构化编程的一种，主要思想是把运算过程尽量写成一系列嵌套的函数调用</li>
<li>函数式编程中，将函数也当做数据类型，因此可以接收函数当做输入（参数）和输出（返回值）</li>
<li>函数式编程中，最重要的就是函数（function)</li>
</ul>
<h4 id="5-1-1-函数和方法的关系"><a href="#5-1-1-函数和方法的关系" class="headerlink" title="5.1.1 函数和方法的关系"></a>5.1.1 函数和方法的关系</h4><ul>
<li>在Scala中，方法和函数几乎可以等同（比如它们的定义、使用、运行机制都一样），只是函数的使用方式更加的灵活多样</li>
<li>函数式编程是从编程方式（范式）的角度来谈的，可以理解为函数式编程把函数当做一等公民，充分利用函数、支持函数的多种使用方式</li>
<li>面向对象编程是以对象为基础的编程方式</li>
<li>在Scala中函数式编程和面向对象编程融合在一起</li>
</ul>
<blockquote>
<p>函数式编程的好处：可以重复调用，减少相同功能的代码量，有利与后期的维护</p>
</blockquote>
<h3 id="5-2-函数的定义"><a href="#5-2-函数的定义" class="headerlink" title="5.2 函数的定义"></a>5.2 函数的定义</h3><h4 id="5-2-1-基本语法"><a href="#5-2-1-基本语法" class="headerlink" title="5.2.1 基本语法"></a>5.2.1 基本语法</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">def</span> 函数名 <span class="token punctuation">(</span><span class="token punctuation">[</span>参数名<span class="token operator">:</span> 参数类型<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token operator">:</span> 返回值类型<span class="token punctuation">]</span> <span class="token operator">=</span><span class="token punctuation">]</span><span class="token punctuation">{</span>
    语句<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token keyword">return</span> 返回值
<span class="token punctuation">}</span>
</code></pre>
<ol>
<li>函数声明关键字为def（definition）</li>
<li>[参数名: 参数类型], … 表示函数的输入（参数列表），可以没有。如果有多个参数使用逗号间隔</li>
<li>函数中的语句：表示为了实现某一功能代码块</li>
<li>函数可以有返回值，也可以没有</li>
<li>返回值形式1：: 返回值类型 =</li>
<li>返回值形式2：= 表示返回值类型不确定，使用类型推导式完成</li>
<li>返回值形式3：表示没有返回值，return 不生效</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fun

<span class="token keyword">object</span> FunDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> n1 <span class="token operator">=</span> <span class="token number">10</span>
    <span class="token keyword">val</span> n2 <span class="token operator">=</span> <span class="token number">20</span>
    println<span class="token punctuation">(</span>getResult<span class="token punctuation">(</span>n1<span class="token punctuation">,</span> n2<span class="token punctuation">,</span> <span class="token string">'-'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>getResult<span class="token punctuation">(</span>n1<span class="token punctuation">,</span> n2<span class="token punctuation">,</span> <span class="token string">'*'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token comment" spellcheck="true">// 定义函数/方法</span>
  <span class="token keyword">def</span> getResult<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> n2<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> oper<span class="token operator">:</span> <span class="token builtin">Char</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Any</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>oper <span class="token operator">==</span> <span class="token string">'+'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      n1 <span class="token operator">+</span> n2
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>oper <span class="token operator">==</span> <span class="token string">'-'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      n1 <span class="token operator">-</span> n2
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">// 返回null</span>
      <span class="token keyword">null</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="5-3-函数-调用机制"><a href="#5-3-函数-调用机制" class="headerlink" title="5.3 函数-调用机制"></a>5.3 函数-调用机制</h3><h4 id="5-3-1-函数-调用过程"><a href="#5-3-1-函数-调用过程" class="headerlink" title="5.3.1 函数-调用过程"></a>5.3.1 函数-调用过程</h4><p><img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/image-20210425180311919.png" alt="示意图"></p>
<h4 id="5-3-2-小结"><a href="#5-3-2-小结" class="headerlink" title="5.3.2 小结"></a>5.3.2 小结</h4><ol>
<li>程序执行一个函数时，就创建一个新的受保护的独立空间（新函数栈）</li>
<li>函数的局部变量是独立的，不会相互影响</li>
<li>递归必须向退出递归的条件逼近，否则就是无限递归</li>
<li>当一个函数执行完毕，或者遇到return，就会返回，遵守谁调用，就将结果返回给谁</li>
</ol>
<h3 id="5-4-函数的注意事项和细节讨论"><a href="#5-4-函数的注意事项和细节讨论" class="headerlink" title="5.4 函数的注意事项和细节讨论"></a>5.4 函数的注意事项和细节讨论</h3><ol>
<li>函数的形参列表可以是多个，如果函数没有形参，调用时，可以不带()</li>
<li>形参列表和返回值列表的数据类型可以是值类型和引用类型</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> Details01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 形参列表和返回值列表的数据类型可以是值类型和引用类型</span>
    <span class="token keyword">val</span> tiger <span class="token operator">=</span> <span class="token keyword">new</span> Tiger
    <span class="token keyword">val</span> tiger2 <span class="token operator">=</span> test01<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> tiger<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>tiger2<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>tiger<span class="token punctuation">.</span>name<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>tiger<span class="token punctuation">.</span>hashCode<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> tiger2<span class="token punctuation">.</span>hashCode<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">def</span> test01<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span>tiger<span class="token operator">:</span> Tiger<span class="token punctuation">)</span><span class="token operator">:</span> Tiger <span class="token operator">=</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span><span class="token string">"n1="</span> <span class="token operator">+</span> n1<span class="token punctuation">)</span>
    tiger<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"jack"</span>
    tiger
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>

<span class="token keyword">class</span> Tiger <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// 一个名字属性</span>
  <span class="token keyword">var</span> name <span class="token operator">=</span> <span class="token string">""</span>
<span class="token punctuation">}</span>
</code></pre>
<ol start="3">
<li>Scala中的函数可以根据函数体最后一行代码自行推断函数返回值类型，这种情况下，return关键字可以省略</li>
<li>Scala可以自行推断，所以在省略return关键字的场合，返回值类型也可以省略</li>
<li>如果函数明确使用return关键字，那么函数返回就不能使用自行推断了，如果什么都不写，则会return ()</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> Details02 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span>getSum<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>getSum2<span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">39</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token comment" spellcheck="true">// 如果写了return，返回值类型就不能省略</span>
  <span class="token keyword">def</span> getSum<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> n2<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> n1 <span class="token operator">+</span> n2
  <span class="token punctuation">}</span>

  <span class="token comment" spellcheck="true">// 如果返回值这里什么都没有写（声明Unit），即表示该函数没有返回值，这时return无效</span>
  <span class="token keyword">def</span> getSum2<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> n2<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> n1 <span class="token operator">+</span> n2
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<ol start="6">
<li>如果函数明确声明无返回值（声明 Unit），那么函数体中即使使用return关键字也不会有返回值</li>
<li>如果明确函数无返回值或不确定返回值类型，那么返回值类型可以省略（或声明为 Any）</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">def</span> f3<span class="token punctuation">(</span>s<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span>length <span class="token operator">>=</span> <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        s <span class="token operator">+</span> <span class="token string">"123"</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        <span class="token number">3</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">def</span> f3<span class="token punctuation">(</span>s<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Any</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span>length <span class="token operator">>=</span> <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        s <span class="token operator">+</span> <span class="token string">"123"</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        <span class="token number">3</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<ol start="8">
<li>Scala语法中任何的语法结构都可以嵌套其他语法结构（灵活），即：函数中可以再声明/定义函数，类中可以再声明类，方法中可以再声明/定义方法</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> Details03 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>

    <span class="token keyword">def</span> f1<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// private final</span>
      println<span class="token punctuation">(</span><span class="token string">"f1"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    sayHello<span class="token punctuation">(</span><span class="token punctuation">)</span>
    f1<span class="token punctuation">(</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"0k~~~"</span><span class="token punctuation">)</span>
    <span class="token keyword">def</span> sayHello<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>  <span class="token comment" spellcheck="true">// private final sayHello$1</span>
      println<span class="token punctuation">(</span><span class="token string">"main sayHello"</span><span class="token punctuation">)</span>
      sayHello<span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token keyword">def</span> sayHello<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// private final sayHello$1</span>
        println<span class="token punctuation">(</span><span class="token string">"sayHello sayHello"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>

  <span class="token keyword">def</span> sayHello<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 成员</span>
    println<span class="token punctuation">(</span><span class="token string">"main sayHello1"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<ol start="9">
<li>Scala函数的形参，在声明参数时，直接赋初始值（默认值），这时调用函数时，如果没有指定实参，则会使用默认值。如果指定了实参，则实参会覆盖默认值</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> Details04 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span>sayOk<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>sayOk<span class="token punctuation">(</span><span class="token string">"mary"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  
  <span class="token comment" spellcheck="true">// name 形参的默认值Jack</span>
  <span class="token keyword">def</span> sayOk<span class="token punctuation">(</span>name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"Jack"</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> name <span class="token operator">+</span> <span class="token string">" ok"</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<ol start="10">
<li>如果函数存在多个参数，每一个参数都可以设定默认值，那么这个时候，传递的参数到底是覆盖默认值，还是赋值给没有默认值的参数，就不确定了（默认按照声明顺序【从左到右】）这种情况下，可以使用带名参数</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> DetailsParameter05 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    mysqlCon<span class="token punctuation">(</span><span class="token punctuation">)</span>
    mysqlCon<span class="token punctuation">(</span><span class="token string">"127.0.0.1"</span><span class="token punctuation">,</span> <span class="token number">7777</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 从左到右覆盖</span>
    <span class="token comment" spellcheck="true">// 如果希望指定覆盖某个值，则使用带名参数即可</span>
    mysqlCon<span class="token punctuation">(</span>pwd <span class="token operator">=</span> <span class="token string">"passwd"</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">//    f6("v2")</span>
    f6<span class="token punctuation">(</span>p2 <span class="token operator">=</span> <span class="token string">"v2"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">def</span> mysqlCon<span class="token punctuation">(</span>add<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"localhost"</span><span class="token punctuation">,</span> port<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token number">3306</span><span class="token punctuation">,</span>
               user<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"root"</span><span class="token punctuation">,</span> pwd<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"root"</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span><span class="token string">"add="</span> <span class="token operator">+</span> add<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"port="</span> <span class="token operator">+</span> port<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"user="</span> <span class="token operator">+</span> user<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span><span class="token string">"pwd="</span> <span class="token operator">+</span> pwd<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">def</span> f6<span class="token punctuation">(</span>p1<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">"v1"</span><span class="token punctuation">,</span> p2<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span>p1 <span class="token operator">+</span> p2<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<ol start="11">
<li>递归函数未执行之前是无法推断出来结果类型，在使用时必须有明确的返回值类型</li>
<li>Scala函数支持可变函数（可变参数需要写在形参列表的最后）</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>fundetails

<span class="token keyword">object</span> VarParameters <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 编写一个函数sum，可以求出 1 到多个int的和</span>
    println<span class="token punctuation">(</span>sum<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token number">40</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token comment" spellcheck="true">// 可变参数需要放在最后</span>
  <span class="token keyword">def</span> sum<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> args <span class="token operator">:</span> <span class="token builtin">Int</span><span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span><span class="token string">"args.length="</span> <span class="token operator">+</span> args<span class="token punctuation">.</span>length<span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 遍历</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> n1
    <span class="token keyword">for</span> <span class="token punctuation">(</span>item <span class="token keyword">&lt;-</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      sum <span class="token operator">+=</span> item
    <span class="token punctuation">}</span>
    sum
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="5-5-过程"><a href="#5-5-过程" class="headerlink" title="5.5 过程"></a>5.5 过程</h3><blockquote>
<p>将函数的返回类型为 Unit 的函数称之为过程，如果明确函数没有返回值，那么等号可以省略</p>
</blockquote>
<p>注意事项：</p>
<ul>
<li>如果函数声明时没有返回值类型，但是有 = 号，可以进行类型推断最后一行代码。这时函数实际是有返回值的，该函数并不是过程。</li>
<li>开发工具的自动代码补全功能，虽然会自动加上Unit，但是考虑到Scala语言的简单，灵活，最好不加。</li>
</ul>
<h3 id="5-6-惰性函数"><a href="#5-6-惰性函数" class="headerlink" title="5.6 惰性函数"></a>5.6 惰性函数</h3><blockquote>
<p>当函数返回值被声明为 lazy 时，函数的执行将被推迟，直到我们首次对此取值，该函数才会执行</p>
</blockquote>
<h4 id="5-6-1-注意事项"><a href="#5-6-1-注意事项" class="headerlink" title="5.6.1 注意事项"></a>5.6.1 注意事项</h4><ul>
<li>lazy 不能修饰 var 类型的变量</li>
<li>不但是在调用函数时，加了lazy会导致函数的执行被推迟，我们在声明一个变量时，如果声明了lazy，那么变量值的分配也会推迟</li>
</ul>
<h4 id="5-6-2-应用场景"><a href="#5-6-2-应用场景" class="headerlink" title="5.6.2 应用场景"></a>5.6.2 应用场景</h4><p><code>惰性计算</code>（尽可能延迟表达式求值）是许多函数式编程语言的特性。惰性集合在需要时提供其元素，无需预先计算它们，这带来了一些好处。首先，可以将耗时的计算推迟到绝对需要的时候。其次，可以创造无限个集合，只要它们继续收到请求，就会继续提供元素。函数的惰性使用能过得到更高效的代码。</p>
<h3 id="5-7-异常"><a href="#5-7-异常" class="headerlink" title="5.7 异常"></a>5.7 异常</h3><blockquote>
<p>Scala提供try和catch块来处理异常。try块用于包含可能出错的代码 。catch块用于处理try块中发生的异常。可以根据需要在程序中使用任意数量的try…catch块。</p>
</blockquote>
<h4 id="5-7-1-Scala异常处理举例"><a href="#5-7-1-Scala异常处理举例" class="headerlink" title="5.7.1 Scala异常处理举例"></a>5.7.1 Scala异常处理举例</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>myexception

<span class="token keyword">object</span> ScalaExceptionDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>

    <span class="token keyword">try</span> <span class="token punctuation">{</span>
      <span class="token keyword">val</span> r <span class="token operator">=</span> <span class="token number">10</span> <span class="token operator">/</span> <span class="token number">0</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">/*
        1.在Scala中只有一个catch
        2.在catch中有多个case，每个case可以匹配一种异常
       */</span>
      <span class="token keyword">case</span> ex<span class="token operator">:</span> ArithmeticException <span class="token keyword">=></span> println<span class="token punctuation">(</span><span class="token string">"捕获除数为零的算数异常"</span><span class="token punctuation">)</span>
      <span class="token keyword">case</span> exception<span class="token operator">:</span> Exception <span class="token keyword">=></span> println<span class="token punctuation">(</span><span class="token string">"捕获了异常"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
      <span class="token comment" spellcheck="true">// 最终要执行的代码</span>
      println<span class="token punctuation">(</span><span class="token string">"Scala finally..."</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h4 id="5-7-2-Scala异常处理小结"><a href="#5-7-2-Scala异常处理小结" class="headerlink" title="5.7.2 Scala异常处理小结"></a>5.7.2 Scala异常处理小结</h4><ol>
<li>我们将可疑代码封装在try块中。 在try块之后使用了一个catch处理程序来捕获异 常。如果发生任何异常，catch处理程序将处理它，程序将不会异常终止。</li>
<li>Scala的异常的工作机制和Java一样，但是Scala没有“checked(编译时)”异常，即 Scala没有编译异常这个概念，异常<em>都是在运行的时候捕获</em>处理。</li>
<li>用throw关键字，抛出一个异常对象。所有异常都是Throwable的子类型。throw 表达式是有类型的，就是Nothing，因为Nothing是所有类型的子类型，所以 throw表达式可以用在需要类型的地方 </li>
<li>在Scala里，借用了模式匹配的思想来做异常的匹配，因此，在catch的代码里，是 一系列case子句来匹配异常，当匹 配上后 =&gt; 有多条语句可以换行写，类似 java 的 switch case x: 代码块..</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>myexception

<span class="token keyword">object</span> ThrowDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token comment" spellcheck="true">//    val res = test()</span>
<span class="token comment" spellcheck="true">//    println(res.toString)</span>

    <span class="token comment" spellcheck="true">// 如果我们希望在test()抛出异常后，代码可以继续执行，则我们需要处理</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
      test<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">{</span>
      <span class="token keyword">case</span> exception<span class="token operator">:</span> Exception <span class="token keyword">=></span> <span class="token punctuation">{</span>
        println<span class="token punctuation">(</span><span class="token string">"捕获到异常"</span> <span class="token operator">+</span> exception<span class="token punctuation">.</span>getMessage<span class="token punctuation">)</span>
        println<span class="token punctuation">(</span><span class="token string">"xxx"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>

    <span class="token punctuation">}</span>

    println<span class="token punctuation">(</span><span class="token string">"ok~~~"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">def</span> test<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Nothing</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> Exception<span class="token punctuation">(</span><span class="token string">"异常出现~"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<ol start="5">
<li><p>异常捕捉的机制与其他语言中一样，如果有异常发生，catch子句是按次序捕捉的。 因此，在catch子句中，越具体的异常越要靠前，越普遍的异常越靠后，如果把越 普遍的异常写在前，把具体的异常写在后，在scala中也不会报错，但这样是非常 不好的编程风格</p>
</li>
<li><p>finally子句用于执行不管是正常处理还是有异常发生时都需要执行的步骤，一般 用于对象的清理工作，这点和Java一样</p>
</li>
<li><p>Scala提供了throws关键字来声明异常。可以使用方法定义声明异常。 它向调用者函数提供了此方法可能引发此异常的信息。 它有助于调用函数处理并将该代码包 含在try-catch块中，<strong>以避免程序异常终止</strong>。在scala中，可以使用throws注释声明异常</p>
</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter05<span class="token punctuation">.</span>myexception

<span class="token keyword">object</span> ThrowsComment <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    f11<span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token annotation punctuation">@throws</span><span class="token punctuation">(</span>classOf<span class="token punctuation">[</span>NumberFormatException<span class="token punctuation">]</span><span class="token punctuation">)</span>
  <span class="token keyword">def</span> f11<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token string">"abc"</span><span class="token punctuation">.</span>toInt
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="第六章-面向对象编程"><a href="#第六章-面向对象编程" class="headerlink" title="第六章 面向对象编程"></a>第六章 面向对象编程</h2><h3 id="6-1-类与对象"><a href="#6-1-类与对象" class="headerlink" title="6.1 类与对象"></a>6.1 类与对象</h3><h4 id="6-1-1-初使用"><a href="#6-1-1-初使用" class="headerlink" title="6.1.1 初使用"></a>6.1.1 初使用</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>oop

<span class="token keyword">object</span> CatDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>

    <span class="token comment" spellcheck="true">// 创建一只猫</span>
    <span class="token keyword">val</span> cat <span class="token operator">=</span> <span class="token keyword">new</span> Cat
    <span class="token comment" spellcheck="true">// 给猫的属性赋值</span>
    cat<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"小白"</span>
    cat<span class="token punctuation">.</span>age <span class="token operator">=</span> <span class="token number">5</span>
    cat<span class="token punctuation">.</span>color <span class="token operator">=</span> <span class="token string">"白色"</span>
    println<span class="token punctuation">(</span>s<span class="token string">"这只${cat.color}的猫的名字叫${cat.name}，今年${cat.age}岁"</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 定义一个Cat类</span>
<span class="token comment" spellcheck="true">// 一个class Cat 对应的字节码文件只有一个 Cat.class，默认是 public</span>
<span class="token keyword">class</span> Cat <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// 定义/声明三个属性</span>
  <span class="token comment" spellcheck="true">/*
    1.当我们声明了 var name: String 时，在底层对应 private name
    2.同时会生成两个public方法 name()类似 getter;  public name_$eq() 类似 setter
   */</span>
  <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token string">""</span>
  <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> _ <span class="token comment" spellcheck="true">// _ 表示给age一个默认值</span>
  <span class="token keyword">var</span> color<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> _ <span class="token comment" spellcheck="true">// 表示给color一个默认值</span>
<span class="token punctuation">}</span>
</code></pre>
<h4 id="6-1-2-类和对象的区别和联系"><a href="#6-1-2-类和对象的区别和联系" class="headerlink" title="6.1.2 类和对象的区别和联系"></a>6.1.2 类和对象的区别和联系</h4><ul>
<li><p>类是抽象的，概念的，代表一类事物，比如人类，猫类</p>
</li>
<li><p>对象是具体的，实际的，代表一个具体事物</p>
</li>
<li><p>类是对象的模板，对象是类的一个个体，对应一个实例</p>
</li>
<li><p><strong>类是对象的模板，对象是类的实例。类只有通过对象才可以使用，而在开发之中应该先产生类，之后再产生对象。类不能直接使用，对象是可以直接使用的。</strong></p>
</li>
</ul>
<table>
<thead>
<tr>
<th></th>
<th>类</th>
<th>对象</th>
</tr>
</thead>
<tbody><tr>
<td>定义</td>
<td>将数据以及这些数据上的操作封装在一起</td>
<td>具有类类型的变量</td>
</tr>
<tr>
<td>范畴</td>
<td>抽象概念</td>
<td>类的一个具体</td>
</tr>
<tr>
<td>状态</td>
<td>静态，不携带任何数据，本身不存在内存</td>
<td>动态，拥有自己的属性和行为，属性可随行为发生改变</td>
</tr>
</tbody></table>
<h4 id="6-1-3-类的定义"><a href="#6-1-3-类的定义" class="headerlink" title="6.1.3 类的定义"></a>6.1.3 类的定义</h4><pre class=" language-scala"><code class="language-scala"><span class="token punctuation">[</span>修饰符<span class="token punctuation">]</span> <span class="token keyword">class</span> 类名 <span class="token punctuation">{</span>
    类体
<span class="token punctuation">}</span>
</code></pre>
<ul>
<li>定义类的注意事项<ul>
<li>Scala语法中，类并不声明为public，所有这些类都具有公共性(即默认为public)</li>
<li>一个Scala源文件可以包含多个类，而且默认都是public</li>
</ul>
</li>
</ul>
<h4 id="6-1-4-属性-成员变量"><a href="#6-1-4-属性-成员变量" class="headerlink" title="6.1.4 属性/成员变量"></a>6.1.4 属性/成员变量</h4><ol>
<li>属性的定义语法同变量，例：[访问修饰符] var 属性名称 [: 类型] = 属性值</li>
<li>属性的定义可以为任意类型，包含值类型或引用类型</li>
<li>Scala中声明一个属性，必须显示将其初始化，然后根据初始化数据的类型自动推断，属性类型可以省略</li>
<li>如果赋值为null，则一定要加类型，如果不加，则该属性的类型就是Null类型</li>
<li>如果在定义属性时，暂时不赋值，也可以使用符号_（下划线）让系统分配默认值</li>
</ol>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">class</span> A <span class="token punctuation">{</span>
    <span class="token keyword">var</span> var1<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> _  <span class="token comment" spellcheck="true">// null</span>
    <span class="token keyword">var</span> var2<span class="token operator">:</span> <span class="token builtin">Byte</span> <span class="token operator">=</span> _  <span class="token comment" spellcheck="true">// 0</span>
    <span class="token keyword">var</span> var3<span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> _  <span class="token comment" spellcheck="true">// 0.0</span>
    <span class="token keyword">var</span> var4<span class="token operator">:</span> <span class="token builtin">Boolean</span> <span class="token operator">=</span> _  <span class="token comment" spellcheck="true">// false</span>
<span class="token punctuation">}</span>
</code></pre>
<h4 id="6-1-5-创建对象"><a href="#6-1-5-创建对象" class="headerlink" title="6.1.5 创建对象"></a>6.1.5 创建对象</h4><blockquote>
<p>基本语法：</p>
<p>val | var 对象名 [: 类型] = new 类型()</p>
</blockquote>
<ul>
<li>如果不希望改变对象的引用（内存地址）应该声明为 val 性质，否则为 var</li>
<li>Scala在声明对象变量时，可以根据创建对象的类型自动推断，所以类型声明可以省略，<strong>但当类型和后面 new 对象类型有继承关系即多态时，就必须写</strong></li>
</ul>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>oop

<span class="token keyword">object</span> CreateObj <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> emp <span class="token operator">=</span> <span class="token keyword">new</span> Emp  <span class="token comment" spellcheck="true">// emp 类型就是Emp</span>
    <span class="token comment" spellcheck="true">// 如果我们希望将子类对象，交给父类的引用，这时就需要写上类型</span>
    <span class="token keyword">val</span> emp2<span class="token operator">:</span> Person2 <span class="token operator">=</span> <span class="token keyword">new</span> Emp


  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>

<span class="token keyword">class</span> Person2 <span class="token punctuation">{</span>

<span class="token punctuation">}</span>

<span class="token keyword">class</span> Emp <span class="token keyword">extends</span> Person2 <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre>
<h3 id="6-2-方法"><a href="#6-2-方法" class="headerlink" title="6.2 方法"></a>6.2 方法</h3><h4 id="6-2-1-基本说明"><a href="#6-2-1-基本说明" class="headerlink" title="6.2.1 基本说明"></a>6.2.1 基本说明</h4><blockquote>
<p>Scala中的方法其实就是函数</p>
</blockquote>
<h4 id="6-2-2-基本语法"><a href="#6-2-2-基本语法" class="headerlink" title="6.2.2 基本语法"></a>6.2.2 基本语法</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">def</span> 方法名<span class="token punctuation">(</span>参数列表<span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token operator">:</span> 返回值类型<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    方法体
<span class="token punctuation">}</span>
</code></pre>
<h4 id="6-2-3-方法案例演示"><a href="#6-2-3-方法案例演示" class="headerlink" title="6.2.3 方法案例演示"></a>6.2.3 方法案例演示</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>method

<span class="token keyword">object</span> MethodDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 使用</span>
    <span class="token keyword">val</span> dog <span class="token operator">=</span> <span class="token keyword">new</span> Dog
    println<span class="token punctuation">(</span>dog<span class="token punctuation">.</span>cal<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>


<span class="token keyword">class</span> Dog <span class="token punctuation">{</span>
  <span class="token keyword">private</span> <span class="token keyword">var</span> sal<span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> _
  <span class="token keyword">var</span> food<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> _

  <span class="token comment" spellcheck="true">// 方法</span>
  <span class="token keyword">def</span> cal<span class="token punctuation">(</span>n1<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> n2<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    n1 <span class="token operator">+</span> n2
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>method

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn

<span class="token comment" spellcheck="true">/*
  编写方法：判断一个数是奇数还是偶数
 */</span>
<span class="token keyword">object</span> Exercise03 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> n <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">val</span> o <span class="token operator">=</span> <span class="token keyword">new</span> Odd
    o<span class="token punctuation">.</span>num<span class="token punctuation">(</span>n<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> Odd <span class="token punctuation">{</span>

  <span class="token comment" spellcheck="true">// 定义num方法</span>
  <span class="token keyword">def</span> num<span class="token punctuation">(</span>n<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>s<span class="token string">"$n 是偶数"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      println<span class="token punctuation">(</span>s<span class="token string">"$n 是奇数"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="6-3-类和对象应用实例"><a href="#6-3-类和对象应用实例" class="headerlink" title="6.3 类和对象应用实例"></a>6.3 类和对象应用实例</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>dogcase
<span class="token comment" spellcheck="true">/*
  编写一个DogTest类，包含name(String)、age(Int)、weight(Double)属性
  类中声明一个say方法，返回String类型，方法返回信息中包含所有属性值。
  在另一个DogCaseTest类中的main方法中，创建Dog对象，并访问say方法和所有属性，
  将调用结果打印输出。
 */</span>
<span class="token keyword">object</span> DogCaseTest <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> dog <span class="token operator">=</span> <span class="token keyword">new</span> DogTest
    dog<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"TomCat"</span>
    dog<span class="token punctuation">.</span>age <span class="token operator">=</span> <span class="token number">4</span>
    dog<span class="token punctuation">.</span>weight <span class="token operator">=</span> <span class="token number">12.34</span>
    println<span class="token punctuation">(</span>dog<span class="token punctuation">.</span>say<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> DogTest <span class="token punctuation">{</span>
  <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> _
  <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> _
  <span class="token keyword">var</span> weight<span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> _

  <span class="token keyword">def</span> say<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    s<span class="token string">"小狗的信息入下：name=${name}，age=${this.age}，"</span> <span class="token operator">+</span>
      s<span class="token string">"weight=${this.weight}"</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>ticketcase
<span class="token comment" spellcheck="true">/*
  一个景区根据游人的年龄收取不同价 格的门票。
  2) 请编写游人类，根据年龄段决定能够 购买的门票价格并输出
  3) 规则：年龄>18 , 门票为20元，其它情 况免费。
  4) 可以循环从控制台输入名字和年龄， 打印门票收费情况,
  如果名字输入 n , 则退出程序。
 */</span>
<span class="token keyword">import</span> scala<span class="token punctuation">.</span>io<span class="token punctuation">.</span>StdIn
<span class="token keyword">import</span> scala<span class="token punctuation">.</span>util<span class="token punctuation">.</span>control<span class="token punctuation">.</span>Breaks<span class="token punctuation">.</span><span class="token punctuation">{</span>break<span class="token punctuation">,</span> breakable<span class="token punctuation">}</span>

<span class="token keyword">object</span> TicketCaseTest <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> v <span class="token operator">=</span> <span class="token keyword">new</span> Visitor
    v

  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> Visitor <span class="token punctuation">{</span>
  <span class="token keyword">val</span> b <span class="token operator">=</span> <span class="token boolean">true</span>
  breakable <span class="token punctuation">{</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>b<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      print<span class="token punctuation">(</span><span class="token string">"请输入姓名："</span><span class="token punctuation">)</span>
      <span class="token keyword">val</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readLine<span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>name <span class="token operator">==</span> <span class="token string">"n"</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        break
      <span class="token punctuation">}</span>
      print<span class="token punctuation">(</span><span class="token string">"请输入年龄："</span><span class="token punctuation">)</span>
      <span class="token keyword">val</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> StdIn<span class="token punctuation">.</span>readInt<span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>age <span class="token operator">></span> <span class="token number">18</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">val</span> ticketPrice <span class="token operator">=</span> <span class="token number">20</span>
        println<span class="token punctuation">(</span>s<span class="token string">"${name}的年龄为：${age}，门票价格为：$ticketPrice"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        println<span class="token punctuation">(</span>s<span class="token string">"${name}的年龄为：${age}，门票免费"</span><span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  println<span class="token punctuation">(</span><span class="token string">"退出程序"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="6-4-构造器"><a href="#6-4-构造器" class="headerlink" title="6.4 构造器"></a>6.4 构造器</h3><h4 id="6-4-1-简单介绍"><a href="#6-4-1-简单介绍" class="headerlink" title="6.4.1 简单介绍"></a>6.4.1 简单介绍</h4><blockquote>
<p>构造器(constructor)又叫构造方法，是类的一种特殊的方法，它的主要作用是完成新对象的初始化</p>
<p>Scala构造对象也需要调用构造方法，并且可以有任意多个构造方法（支持重载）</p>
<p>Scala类的构造器包括：主构造器和辅助构造器</p>
</blockquote>
<h4 id="6-4-2-构造器的基本语法"><a href="#6-4-2-构造器的基本语法" class="headerlink" title="6.4.2 构造器的基本语法"></a>6.4.2 构造器的基本语法</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">class</span> 类名<span class="token punctuation">(</span>形参列表<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 主构造器</span>
    <span class="token comment" spellcheck="true">// 类体</span>
    <span class="token keyword">def</span> <span class="token keyword">this</span><span class="token punctuation">(</span>形参列表<span class="token punctuation">)</span> <span class="token punctuation">{</span>  <span class="token comment" spellcheck="true">// 辅助构造器</span>
    
    <span class="token punctuation">}</span>
    <span class="token keyword">def</span> <span class="token keyword">this</span><span class="token punctuation">(</span>形参列表<span class="token punctuation">)</span> <span class="token punctuation">{</span>  <span class="token comment" spellcheck="true">// 辅助构造器可以有多个，通过不同的参数来区分</span>
    
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h4 id="6-4-3-Scala构造器的快速入门"><a href="#6-4-3-Scala构造器的快速入门" class="headerlink" title="6.4.3 Scala构造器的快速入门"></a>6.4.3 Scala构造器的快速入门</h4><pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>constructor

<span class="token keyword">object</span> ConDemo01 <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token comment" spellcheck="true">//    val p1 = new Person("jack", 30)</span>
<span class="token comment" spellcheck="true">//    println(p1)</span>

    <span class="token comment" spellcheck="true">// 下面这就话就会调用 def this(name: String)</span>
    <span class="token keyword">val</span> p2 <span class="token operator">=</span> <span class="token keyword">new</span> Person<span class="token punctuation">(</span><span class="token string">"Tom"</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>p2<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 构造器快速入门</span>
<span class="token keyword">class</span> Person<span class="token punctuation">(</span>inName<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> inAge<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> inName
  <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> inAge

  <span class="token comment" spellcheck="true">// 重写toString，便于输出对象的信息</span>
  <span class="token keyword">override</span> <span class="token keyword">def</span> toString<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token string">"name="</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">+</span> <span class="token string">" age="</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>age
  <span class="token punctuation">}</span>
  println<span class="token punctuation">(</span><span class="token string">"age="</span> <span class="token operator">+</span> age<span class="token punctuation">)</span>
  println<span class="token punctuation">(</span><span class="token string">"name="</span> <span class="token operator">+</span> name<span class="token punctuation">)</span>
  <span class="token keyword">def</span> <span class="token keyword">this</span><span class="token punctuation">(</span>name<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// 辅助构造器必须在第一行显式调用主构造器（直接或间接）</span>
    <span class="token keyword">this</span><span class="token punctuation">(</span><span class="token string">"jack"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="6-5-属性高级"><a href="#6-5-属性高级" class="headerlink" title="6.5 属性高级"></a>6.5 属性高级</h3><h4 id="6-5-1-构造器参数"><a href="#6-5-1-构造器参数" class="headerlink" title="6.5.1 构造器参数"></a>6.5.1 构造器参数</h4><ul>
<li><p>Scala类的主构造器的形参未用任何修饰符修饰，那么这个参数是局部变量</p>
</li>
<li><p>如果参数使用val关键字声明，那么Scala会将参数作为类的私有的只读属性</p>
</li>
<li><p>如果参数使用var关键字声明，那么那么Scala会将参数作为类的<strong>成员属性</strong>使 </p>
<p>用,并会提供属性对应的xxx()[类似getter]/xxx_$eq()[类似setter]方法，即这时 </p>
<p>的<strong>成员属性是私有的，但是可读写</strong></p>
</li>
</ul>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>constructor

<span class="token keyword">object</span> ConDemo04 <span class="token punctuation">{</span>

  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> worker <span class="token operator">=</span> <span class="token keyword">new</span> Worker<span class="token punctuation">(</span><span class="token string">"smith"</span><span class="token punctuation">)</span>
    worker<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"cik"</span>
    println<span class="token punctuation">(</span>worker<span class="token punctuation">.</span>name<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true">// 不能访问inName</span>

    <span class="token keyword">val</span> worker2 <span class="token operator">=</span> <span class="token keyword">new</span> Worker2<span class="token punctuation">(</span><span class="token string">"smith2"</span><span class="token punctuation">)</span>
    worker2<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"sdf"</span>
<span class="token comment" spellcheck="true">//    worker2.inName = "Tom" 不能写</span>
    println<span class="token punctuation">(</span>worker2<span class="token punctuation">.</span>inName<span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>worker2<span class="token punctuation">.</span>name<span class="token punctuation">)</span>

    <span class="token keyword">val</span> worker3 <span class="token operator">=</span> <span class="token keyword">new</span> Worker3<span class="token punctuation">(</span><span class="token string">"Jack"</span><span class="token punctuation">)</span>
    worker3<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"sdf"</span>
    worker3<span class="token punctuation">.</span>inName <span class="token operator">=</span> <span class="token string">"sdh"</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// 1.如果主构造器是Worker(inName: String)，那么 inName就是一个局部变量</span>
<span class="token keyword">class</span> Worker<span class="token punctuation">(</span>inName<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> name <span class="token operator">=</span> inName
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 1.如果主构造器是Worker(val inName: String)，那么 inName就是Worker2的一个private的只读属性</span>
<span class="token keyword">class</span> Worker2<span class="token punctuation">(</span><span class="token keyword">val</span> inName<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> name <span class="token operator">=</span> inName
<span class="token punctuation">}</span>


<span class="token comment" spellcheck="true">// 1.如果主构造器是Worker(var inName: String)，那么 inName就是Worker2的一个private的可读写属性</span>
<span class="token keyword">class</span> Worker3<span class="token punctuation">(</span><span class="token keyword">var</span> inName<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> name <span class="token operator">=</span> inName
<span class="token punctuation">}</span>
</code></pre>
<h4 id="6-5-2-Bean-属性"><a href="#6-5-2-Bean-属性" class="headerlink" title="6.5.2 Bean 属性"></a>6.5.2 Bean 属性</h4><blockquote>
<p>JavaBeans规范定义了Java的属性是像getXxx（）和setXxx（）的方法。许多 Java工具（框架）都依赖这个命名习惯。为了Java的互操作性。将Scala字段 加@BeanProperty时，这样会自动生成<strong>规范的</strong> <strong>setXxx/getXxx</strong> <strong>方法</strong>。这时可 以使用 对象.setXxx() 和 对象.getXxx() 来调用属性</p>
</blockquote>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">package</span> com<span class="token punctuation">.</span>atguigu<span class="token punctuation">.</span>chapter06<span class="token punctuation">.</span>constructor

<span class="token keyword">import</span> scala<span class="token punctuation">.</span>beans<span class="token punctuation">.</span>BeanProperty

<span class="token keyword">object</span> BeanPropertyDemo <span class="token punctuation">{</span>
  <span class="token keyword">def</span> main<span class="token punctuation">(</span>args<span class="token operator">:</span> Array<span class="token punctuation">[</span><span class="token builtin">String</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Unit</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token keyword">val</span> car <span class="token operator">=</span> <span class="token keyword">new</span> Car
    car<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"BaoMa"</span>
    println<span class="token punctuation">(</span>car<span class="token punctuation">.</span>name<span class="token punctuation">)</span>

    car<span class="token punctuation">.</span>setName<span class="token punctuation">(</span><span class="token string">"奔驰"</span><span class="token punctuation">)</span>
    println<span class="token punctuation">(</span>car<span class="token punctuation">.</span>getName<span class="token punctuation">)</span>

  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> Car <span class="token punctuation">{</span>
  <span class="token annotation punctuation">@BeanProperty</span> <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> <span class="token keyword">null</span>
<span class="token punctuation">}</span>
</code></pre>
<h3 id="6-6-Scala对象创建的流程分析"><a href="#6-6-Scala对象创建的流程分析" class="headerlink" title="6.6 Scala对象创建的流程分析"></a>6.6 Scala对象创建的流程分析</h3><pre class=" language-scala"><code class="language-scala"><span class="token keyword">class</span> Person <span class="token punctuation">{</span>
    <span class="token keyword">var</span> age<span class="token operator">:</span> <span class="token builtin">Short</span> <span class="token operator">=</span> <span class="token number">90</span>
    <span class="token keyword">var</span> name<span class="token operator">:</span> <span class="token builtin">String</span> <span class="token operator">=</span> _
    <span class="token keyword">def</span> <span class="token keyword">this</span><span class="token punctuation">(</span>n<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> a<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> n
        <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">=</span> a
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">var</span> p<span class="token operator">:</span> Person <span class="token operator">=</span> <span class="token keyword">new</span> Person<span class="token punctuation">(</span><span class="token string">"小倩"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">/*
流程分析
1.加载类的信息（属性信息，方法信息）
2.在内存中(堆)开辟空间
3.使用父类的构造器(主和辅助)进行初始
4.使用主构造器对属性进行初始化【age: 90, name: null】
5.使用辅助构造器对属性进行初始化【age: 20, name: 小倩】
6.将开辟的对象地址赋给p引用
*/</span>
</code></pre>
<p>79</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Aunean</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.shiyiri.top/node/8.html">https://www.shiyiri.top/node/8.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Aunean</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Scala/">
                                    <span class="chip bg-color">Scala</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: '43918ae8f8557340e530',
        clientSecret: '016469b0d80284ccd95b27ea68909008a765d99e',
        repo: 'comment_by_blog',
        owner: 'Aunean-ls',
        admin: "Aunean-ls",
        id: '2021-05-04T12-04-00',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/node/10.html">
                    <div class="card-image">
                        
                        
                        <img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/u013.webp" class="responsive-img" alt="Spark笔记">
                        
                        <span class="card-title">Spark笔记</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文记录Spark学习时的一些笔记
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-05-09
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="post-category">
                                    学习笔记
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Spark/">
                        <span class="chip bg-color">Spark</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/node/101.html">
                    <div class="card-image">
                        
                        
                        <img src="https://cdn.jsdelivr.net/gh/Aunean-ls/pic/img/u030.webp" class="responsive-img" alt="博客搭建">
                        
                        <span class="card-title">博客搭建</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            收集一些大佬写的搭建方法
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-04-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%9F%BA%E4%BA%8Ehexo%E6%90%AD%E5%BB%BA/" class="post-category">
                                    基于hexo搭建
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/hexo/">
                        <span class="chip bg-color">hexo</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="4628814494"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">Aunean</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">64.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2021";
                    var startMonth = "4";
                    var startDate = "11";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Aunean-ls" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1453357375@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1453357375" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1453357375" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <script type="text/javascript">
        var OriginTitile=document.title,st;
        document.addEventListener("visibilitychange",function(){
            document.hidden?(document.title="ヽ(●-`Д´-)ノ页面丢失了",clearTimeout(st)):(document.title="(Ő∀Ő3)ノ又好了哦！",st=setTimeout(function(){document.title=OriginTitile},3e3))
        })
    </script>


    <script type="text/javascript">
    //只在桌面版网页启用特效
        var windowWidth = $(window).width();
        if (windowWidth > 768) {
            document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
        }
    </script>


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

	
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    


</body>

</html>
